﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Grundy.Client;
using Grundy.Entity;
using Grundy.Message;
using Grundy.Message.Administration;
using log4net;

namespace Grundy.Licensing.Server.Web.Controllers
{
    public class LicenseServerController : Controller
    {
        private static ILog _logger = LogManager.GetLogger(typeof(LicenseServerController));

        public ActionResult Index()
        {
            ViewBag.Hostname = Application.Instance.ClientConfiguration.LicenseServerAddress;
            ViewBag.Port = Application.Instance.ClientConfiguration.LicenseServerPort;
            return View();
        }

        [HttpPost]
        public ActionResult GetInstalledLicensesData(int page = 1, int rows = 0)
        {
            var licenseClient = Application.Instance.GetLicenseClient();
            object data = null;
            try
            {
                Response response = licenseClient.ProcessAdministrationRequest(new GetInstalledLicensesRequest());
                if (response is Error)
                {
                    var error = (Error) response;
                    _logger.ErrorFormat("Was expecting a {0} response but received a {1} response. Message: {2} \r\nDetails: {3}", typeof(InstalledLicensesResponse).Name, response.GetType().Name,  error.Message, error.Details);
                }
                if (response is InstalledLicensesResponse)
                {
                    var adminResponse = (InstalledLicensesResponse) response;

                    data = new
                    {
                        total = page,
                        page = page,
                        records = adminResponse.LicensesData.Count,
                        rows = adminResponse.LicensesData.Skip((page - 1) * rows).Take(rows)
                               .Select((i) => new { Id = i.License.Id, cell = new object[] { i.License.Id, i.Customer, i.License.Name, i.License.Type, i.Product, i.License.Feature.Name, GetLimit(i.License), i.Exhausted } }).ToList()
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorFormat("Error contacting license server. Message: {0} \r\nDetails: {1}", ex.Message, ex.ToString());
            }

            return Json(data);
        }

        private string GetLimit(License license)
        {
            if (license is CountedFloatingLicense)
            {
                var countedFloatingLicense = (CountedFloatingLicense) license;
                return countedFloatingLicense.Limit.ToString();
            }
            return string.Empty;
        }
    }
}
